PLUGIN.Name = "Parallel Worlds"
PLUGIN.DefaultOn = false
PLUGIN.Description = ""
PLUGIN.Trigger = false

function PLUGIN:LoadParameters()
end

function PLUGIN:_Print( ... )
	local args = {...}
	chat.AddText(self.cParallel, "Parallel Worlds", self.cNeutral, " : ", unpack(args) )
end

function PLUGIN:Load()
	self.cParallel = Color(255,0,0)
	self.cNeutral = Color(255,255,255)
	self.cError = Color(192,0,0)
	self.cInfo = Color(0,192,0)
	
	self.tOwners = {}
	self.tHandshaking = {}
	self.tConnected = {}
	
	self:_Print( "Enabling ..." )
	
	RunConsoleCommand("cl_gtalk", " ")
	RunConsoleCommand("cl_msn", "")
	
	self.SubLoaded = false

end

function PLUGIN.HOOK:Tick()
	if not self.SubLoaded then
		self.SubLoaded = true
		self:_Query()
	end
	
	do
		local players = player.GetAll()
		local i = 1
		local foundHandshake = false
		while ((i <= #players) and not foundHandshake) do
			local ply = players[i]
			
			if ply ~= LocalPlayer() then
				if not self.tHandshaking[ ply:UniqueID() ] and ply:GetMSN() == " " then
					self:_Print( self.cInfo, ply:Nick() .. " seems to be initiating a handshake ..." )
					self.tHandshaking[ ply:UniqueID() ] = true
					
					foundHandshake = ply
					
					LocalPlayer():EmitSound("npc/roller/mine/rmine_chirp_quest1.wav")
				end
				
			end
			
			i = i + 1
			
		end
	end
	
	if foundHandshake then
		RunConsoleCommand("cl_xfire", ply:SteamID())
	end
	
	self.tIREMOVE = {}
	for k,ply in pairs( self.tOwners ) do
		if ply:GetXFire() == tostring(LocalPlayer():SteamID()) then
			table.insert( self.tConnected, ply )
			self:_Print( self.cInfo, ply:Nick() .. " is greeting you !" )
			
			LocalPlayer():EmitSound("npc/roller/remote_yes.wav")
		end
		table.insert(self.tIREMOVE, k)
	end
	
	for i,v in pairs(self.tIREMOVE) do
		table.remove( self.tOwners, v - i - 1 )
	end
	
end

function PLUGIN:_Query( )
	
	self:_Print( self.cInfo, "Querying ..." )
	for k,ply in pairs(player.GetAll()) do
		if ply ~= LocalPlayer() and ply:GetGTalk() == " " then
			table.insert(self.tOwners, ply)
		end
	end
	
	if #self.tOwners > 0 then
		self:_Print( self.cInfo, "Found ".. #self.tOwners .. " potential owner" .. ((#self.tOwners > 1) and "s" or "") .. "." )
		for k,ply in pairs(self.tOwners) do
			self:_Print( self.cInfo, ply:Nick() )
			
		end
		
		self:_Print( self.cInfo, "Now sending open handshake ..." )
		RunConsoleCommand("cl_msn", " ")
		
		LocalPlayer():EmitSound("npc/roller/code2.wav")
	
	else
		self:_Print( self.cInfo, "Couldn't find receivers !" )
		
	end
	
end

function PLUGIN:Unload()
	self:_Print( "Disabling ..." )
	RunConsoleCommand("cl_gtalk", "")

end
